from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.jobs.jobs_rule  import jobs_rule_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.jobs import JobsRuleCreate, JobsRuleUpdate
from app.settings import settings


jobs_rule_router = APIRouter()
model_name = "定时规则"

@jobs_rule_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"名称"),
        type: int = Query(0, description="类型"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    if type:
        q &= Q(type=type)
    total, data = await jobs_rule_controller.do_list(page=page, page_size=page_size, search=q)
    for item in data:
        item["type_name"] = settings.JOBS_TYPE[item["type"]]
        if item["type"] ==1:
            item["rule_name"] = f"每{item["times"]}秒执行"
        else:
            rule_name = ""
            if item["day"] > 0:
                rule_name += f"{item["day"]}号"
            if item["hour"] > 0:
                rule_name += f"{item["hour"]}点"
            if item["minute"]>0:
                rule_name+=f"{item["minute"]}分"
            if item["second"]>0:
                rule_name+=f"{item["second"]}秒"

            item["rule_name"] = f"{rule_name}执行"

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@jobs_rule_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await jobs_rule_controller.do_detail(data_id=data_id)
    return Success(data=data)

@jobs_rule_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        category_in: JobsRuleCreate,
):
    await jobs_rule_controller.do_create(obj_in=category_in)
    return Success(msg="创建成功")

@jobs_rule_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        category_in: JobsRuleUpdate,
):
    await jobs_rule_controller.do_update(obj_in=category_in)
    return Success(msg="更新成功")

@jobs_rule_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await jobs_rule_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@jobs_rule_router.get("/type", summary="获取任务类型")
async def list_type():
    level_objs = settings.JOBS_TYPE
    data = []
    key = 0
    for level in level_objs:
        if level:
            data.append({"label":level,"value":key})
        key += 1
    return Success(data=data)

